import { toArray } from '../../util/index'


export function initEvents(vm) {
  vm._events = Object.create(null)
  vm._hasHookEvent = false
  // 组件上绑定的事件
  const listeners = vm.$options._parentListeners
  if (listeners) {
    updateComponentListeners(vm, listeners)
  }
}

export function updateComponentListeners(
  vm,
  listeners
) {
   for (const key in listeners) {
      const fn = listeners[key];
      vm.$on(key, fn)
   }
}


export function eventsMixin(Vue) {
  Vue.prototype.$on = function (event, fn) {
    const vm = this
    vm._events[event] = fn
    vm._hasHookEvent = true
    return vm
  }

  Vue.prototype.$off = function (event, fn) {
    const vm = this
    //不传参数直接重置_events
    if (!arguments.length) {
      vm._events = Object.create(null)
      return vm
    }
    //不存在的注册事件
    const cbs = vm._events[event]
    if (!cbs) {
      return vm
    }
    //事件命存在，事件不存在，去除
    if (!fn) {
      vm._events[event] = null
      return vm
    }

    if (vm._events[event] === fn || vm._events[event].fn === fn) {
      vm._events[event] = null
    }
    return vm
  }
  Vue.prototype.$emit = function (event) {
    const vm = this
    let cbs = vm._events[event]
    if (cbs) {
      const args = toArray(arguments, 1)
      cbs.apply(vm, args)
    }
    return vm
  }
}